
package com.marketapp.validators;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.marketapp.domain.Equity;
import com.marketapp.helper.ServiceException;
import com.marketapp.service.IEquityService;
import com.marketapp.util.StringUtil;

@Component
public class EquityValidator implements Validator{

	@Override
	public boolean supports(Class<?> clazz) {
		return Equity.class.isAssignableFrom(clazz);
	}
	
	@Autowired
	IEquityService equityService;

	public IEquityService getEquityService() {
		return equityService;
	}

	public void setEquityService(IEquityService equityService) {
		this.equityService = equityService;
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmpty(errors, "equityName", "equity.required");
		ValidationUtils.rejectIfEmpty(errors, "equityBSE", "equityBSE.required");
		ValidationUtils.rejectIfEmpty(errors, "equityNSE", "equityNSE.required");
		ValidationUtils.rejectIfEmpty(errors, "equityISIN", "equityISIN.required");
		Equity equity = (Equity) target;
		if(0==equity.getEquitySector().getSectorId()){
			errors.rejectValue("equitySector.sectorId", "sector.required");
		}
		try {
			if(equityService.checkifEquityExist(equity.getEquityBSE(),equity.getEquityNSE(),equity.getEquityISIN())
					&& !StringUtil.ifBlankorNull(equity.getEquityBSE()) 
					&& !StringUtil.ifBlankorNull(equity.getEquityNSE())
					&& !StringUtil.ifBlankorNull(equity.getEquityISIN())
					&& !StringUtil.ifBlankorNull(equity.getEquityName())){
				errors.reject("equity.exist");
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}
	}

}
